package com.heima.search.service.impl;

import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        // 1.查询当前用户的搜索记录是否包含该关键词
        Query query = Query.query(Criteria
                .where("userId").is(userId)
                .and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        // 如果存在,更新查询的时间
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        // 2.如果不存在则新增查询记录
        // 查询当前搜索记录是否大于10条
        query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);

        ApUserSearch newApUserSearch = new ApUserSearch();
        newApUserSearch.setUserId(userId);
        newApUserSearch.setKeyword(keyword);
        newApUserSearch.setCreatedTime(new Date());

        if (apUserSearches == null || apUserSearches.size() < 10) {
            // 如果当前搜索记录条数少于10,直接插入数据
            mongoTemplate.save(newApUserSearch);
        } else {
            // 如果当前数据不少于10条,替换掉查询时间最早的关键词
            ApUserSearch lastSearch = apUserSearches.get(apUserSearches.size() - 1);

            mongoTemplate.findAndReplace(Query.query(Criteria
                    .where("id").is(lastSearch.getId())),newApUserSearch);
        }


    }
}
